package com.starblink.product.productweb.ui

import android.os.Build
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.isVisible
import com.starblink.android.basic.ext.toastSuccess
import com.starblink.android.basic.ext.toastUI
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.px2dp
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.FlowCountDownTimer
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.CollectProductEvent
import com.starblink.android.basic.util.post.CommonMutateManage
import com.starblink.android.basic.widget.LoadingDialogManager
import com.starblink.android.common.R
import com.starblink.android.common.databinding.ActivityStoreLinkBinding
import com.starblink.android.common.web.WebShowBackActivity
import com.starblink.android.common.web.dialog.WebMoreDialog
import com.starblink.basic.apollo.ext.optional
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.CommUtils
import com.starblink.basic.util.ScreenUtils
import com.starblink.library.widget.product.parity.PriceParityDialog
import com.starblink.library.widget.wishlist.WishlistAddBottomDialog
import com.starblink.library.widget.wishlist.bean.BatchProductArrEntry
import com.starblink.rocketreserver.FetchMerchantWebByIdQuery
import com.starblink.rocketreserver.FetchProductDetailByIdQuery
import com.starblink.rocketreserver.FetchProductListByStdIdQuery
import com.starblink.rocketreserver.FetchStdProductDetailByIdQuery
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.rocketreserver.type.StdProductIdQuery
import com.starblink.share.view.ShareDialog
import com.starblink.share.view.utils.ShareTypeEnum
import com.starblink.share.view.utils.ShareUrlUtils
import com.starblink.store.view.StoreProductCompareDialog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch

@Route(path = RoutePage.Product.PAGE_LINK)
class ProductWebActivity : WebShowBackActivity<ActivityStoreLinkBinding, ProductWebVM>() {

    @Autowired(name = "id")
    @JvmField
    var id: String? = null//唯一id 用作收藏

    @Autowired(name = RoutePage.Product.STANDARD_SPU_ID)
    @JvmField
    var standardSpuIds: String? = null//标品id

    @Autowired(name = RoutePage.Product.TRACE_ID)
    @JvmField
    var traceId: String? = null

    @Autowired(name = RoutePage.Product.COLLECT)
    @JvmField
    var collect: Boolean = false//商品收藏状态

    @Autowired(name = RoutePage.Product.COLLECTED)
    @JvmField
    var collected: Int = -1//商品收藏状态

    @Autowired(name = RoutePage.Product.TYPE)
    @JvmField
    var type: Int = 1//商品类型

    private var imgUrl: String = ""
    var buyButtonScript: String = ""

//    private val balloon by balloon<FunWebBalloonFactory>()
//    private var funWebDialog: FunWebDialog? = null

    override fun initViewBinding(): ActivityStoreLinkBinding {
        return ActivityStoreLinkBinding.inflate(layoutInflater)
    }

    override fun initData() {
        super.initData()

        if (collected != -1) {
            collect = collected == 1
        }

//        if (productId == null) {
//            productId = id
//        }
        if (productId.isNullOrEmpty() && standardSpuIds.isNullOrEmpty()) {
            if (type == 1) {
                productId = id
            } else {
                standardSpuIds = id
            }
        }

        trackView()

        viewBinding.rlBottom.btnAdd.visibleOrGone(true) {}
        viewBinding.rlBottom.btnMore.visibleOrGone(true) {}

        //同步收藏数据
        FlowBus.with<CollectProductEvent>(FlowConst.COLLECT_PRODUCT_EVENT).register(this) {
            if (it.id != null && it.id == id && it.collect != collect) {
                collect = it.collect
                updateCollectState(collect)
            }
        }
        getData()

        updateCollectState(collect)


        viewBinding.rlBottom.btnAdd.setOnClickListener {
            id?.let { it1 ->
                CommonMutateManage.collectProduct(
                    ctx = this,
                    id = it1,
                    type = type,
                    collected = collect,
                    scope = MainScope(),
                    refreshState = {
                        updateCollectState(collect.not())
                    },
                    resultCallback = { res, collected ->
                        if (res) {
                            collect = collected
                            it.trackData(
                                page = SpmPageDef.ProductDetailWebView,
                                element = SpmElementDef.ProductDetailNewBodyCollection,
                                onlyHit = true,
                                params = trackParams()
                                    .plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                                    .plus("result" to if (collect) "0" else "1"),
                            )
                            updateCollectState(collect)

                            viewBinding.addBoard.visibleOrGone(collect) {//展示add board
                                FlowCountDownTimer(time = 2).start(callBack = {
                                }, onFinish = {
                                    viewBinding.addBoard.visibleOrGone(false) {

                                    }
                                })
                                setOnClickListener {
                                    WishlistAddBottomDialog.showAddListDialog(
                                        context,
                                        batchPros = arrayListOf(
                                            BatchProductArrEntry(
                                                id = it1,
                                                type = type,
                                                url = imgUrl
                                            )
                                        )
                                    )
                                }
                            }
                        }
                    }
                )
            }
        }

        viewBinding.rlTop.ivWeb.setOnClickListener {
            //分享商品大卡
            clickFunShare()
        }

        viewBinding.rlTop.ivFresh.setOnClickListener {
            //刷新商品
            showLoadingAnim(true)
            mWebView.guangLoadUrl(mWeburl, ifUseCache)
        }

        viewBinding.rlBottom.tvShowNow.click {
            if (!viewModel.productInfo.value?.selfEmploymentInfo?.selfEmploymentInfoVOF?.buyButtonScript.isNullOrEmpty()) {
                LoadingDialogManager.get().showLoading(this@ProductWebActivity)
                mWebView.evaluateJavascript(viewModel.productInfo.value?.selfEmploymentInfo?.selfEmploymentInfoVOF?.buyButtonScript!!) {
                    viewBinding.rlBottom.tvShowNow.postDelayed({
                        LoadingDialogManager.get().dismissLoading()
                    }, 2000)
                }
//                lifecycleScope.launch(Dispatchers.Main) {
//                    delay(2000L)
//                }
            }
        }

        viewBinding.rlBottom.btnMore.setOnClickListener {
            //更多操作
            WebMoreDialog(
                true,
                subOrNot,
                !viewModel.productInfo.value?.brotherOffers.isNullOrEmpty(),
                clickFollowStore = {
                    //Follow 店铺
                    clickFollowStore(it)
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                pageDef,
                                SpmElementDef.StoreSub
                            ),
                            params = mapOf(
                                "merchantName" to (storeName ?: ""),
                            )
                                .plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                                .plus("result" to if (subOrNot) "0" else "1")
                        )
                    )
                },
                clickShare = {
                    //分享页面
                    clickFunShare()
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                pageDef,
                                SpmElementDef.ShareClickSpm
                            ),
                            params = trackParams()
                        )
                    )
                },
                findSimilar = {
                    //找相似
                    findSimilarGood()
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                pageDef,
                                SpmElementDef.Element_33044
                            ),
                            params = trackParams()
                        )
                    )
                },
                priceCheck = {
                    //比价
                    compareGood()
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                pageDef,
                                SpmElementDef.ProductDetailPriceCheckClick
                            ),
                            params = trackParams()
                        )
                    )
                },
                copyLink = {
                    CommUtils.copyText(mWeburl)
                    toastSuccess("Copied Successfully!")
                },
                toWishList = {
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                pageDef,
                                SpmElementDef.Element_33070
                            ),
                            params = trackParams()
                        )
                    )
                }).show(supportFragmentManager, "product_info")
        }

        viewBinding.rlBottom.llOpenStore.setOnClickListener {
            //跳转浏览器
            CommUtils.openUrlToWeb(mActivity, mWeburl)
        }
    }

    override fun trackView() {
        super.trackView()
        viewBinding.rlBottom.btnAdd.trackData(
            page = pageDef,
            element = SpmElementDef.ProductDetailNewBodyCollection, onlyHit = true,
            params = trackParams()
                .plus("status" to (if (UserDataCenter.isLogin()) "1" else "0"))
                .plus("result" to if (collect) "0" else "1")
        )
        viewBinding.rlBottom.ivBack.trackData(
            pageDef,
            SpmElementDef.ProductLinkPageBack,
            onlyHit = true
        )
    }

    private fun getData() {
        if (storeId == null) {
            if (id != null) {
                //获取商品详情 兜底
                CoroutineScope(Dispatchers.IO).launch {
                    if (type == 1) {
                        val response = SkGqlClient.skQuery(
                            FetchProductDetailByIdQuery(
                                productId = Optional.present(id),
                            ),
                        )
                        if (response?.data != null && response.data!!.fetchProductDetailById != null && response.data!!.fetchProductDetailById!!.productF != null) {
                            MainScope().launch {
                                val productF = response.data!!.fetchProductDetailById!!.productF
                                refreshData(productF)
                            }
                        }
                    } else {
                        val response = SkGqlClient.skQuery(
                            FetchStdProductDetailByIdQuery(
                                stdProdcutIdQuery = StdProductIdQuery(
                                    stdProductId = id ?: "",
                                    Optional.Absent,
                                    Optional.Absent,
                                    Optional.Absent, Optional.Absent, Optional.Absent,
                                    Optional.Absent,
                                    Optional.Absent, Optional.Absent, Optional.Absent,
                                ).optional()
                            ),
                        )
                        if (response?.data != null && response.data!!.fetchStdProductDetailById != null) {
                            MainScope().launch {
                                val productF = response.data!!.fetchStdProductDetailById!!.productF
                                refreshData(productF)
                            }
                        }
                    }
                }
            }
        } else if (storeName.isNullOrEmpty()) {
            //获取店铺信息 兜底
            lifecycleScope.launch(Dispatchers.IO) {
                val response = SkGqlClient.skQuery(
                    FetchMerchantWebByIdQuery(
                        storeId!!,
                    ),
                )
                if (response?.data?.fetchMerchantWebById?.merchantWebVOF != null) {
                    lifecycleScope.launch(Dispatchers.Main) {
                        val merchantWeb = response.data!!.fetchMerchantWebById!!
                        storeId = merchantWeb.merchantWebVOF?.id
                        storeName = merchantWeb?.merchantWebVOF?.merchantName
                        storeLogo = merchantWeb?.merchantWebVOF?.logo
                        subOrNot = merchantWeb?.merchantWebVOF?.subOrNot == true
                        setView()
                        showBottomView()
                    }
                }
            }
        }

//        productId = "18de89670a7f7d3ab558dc40ff3b9d1d"
//        mWeburl =
//            "https://guang.shop/products/6pcs-christmas-tree-pendants-candy-shapes-christmas-decorations"
//        mWebView.guangLoadUrl(mWeburl, false)

        productId?.let {
            //获取商品信息
            viewModel.reqProductDetail(it)
        }
    }

    private fun refreshData(productF: ProductF) {
        showBottomView()
        collect = productF.collected == true
        type = productF.type
        val merchantWeb = productF.merchantWeb
        storeId = merchantWeb?.id
        storeName = merchantWeb?.merchantName
        storeLogo = merchantWeb?.logo
        subOrNot = merchantWeb?.subOrNot == true
        imgUrl = productF.mainImg ?: ""

        setView()
        updateCollectState(collect)
    }

    private fun updateCollectState(collected: Boolean) {
        if (collected) {
            viewBinding.rlBottom.btnAdd.setImageResource(R.drawable.ic_svg_web_collected)
        } else {
            viewBinding.rlBottom.btnAdd.setImageResource(R.mipmap.ic_web_collect2)
        }
    }


    //比价弹框样式1
    private fun compareGood() {
        viewModel.productInfo.value?.let {
            //比价弹框
            if (it.brotherOffers.isNullOrEmpty()) {
                return
            }
            StoreProductCompareDialog(
                this,
                it,
                it.brotherOffers,
                ifEqualHaveTag = true,
                trackPage = SpmPageDef.ProductDetailPriceParity
            ).show(supportFragmentManager, "product_compare")
        }
    }

    //比价弹框样式2
    private fun compareGood2() {
        viewModel.productInfo.value?.let {
            //无效
            if (it.valid == false) {
                if (it.mainImg.isNullOrEmpty() || it.id.isNullOrEmpty()) {
                } else {
                    CommonRoute.toFindSimilarGoods(it.mainImg!!, it.id!!, it.type)
                    SpmTrackHandler.addSingleTrackData(
                        SkAntEntity(
                            spmCnt = GTrackerAssistUtils.fetchElementValue(
                                SpmPageDef.ProductDetailWebView,
                                SpmElementDef.Element_33044
                            ),
                            params = trackParams()
                        )
                    )
                }
            } else {
                showParityDialog(it)
            }
        }
    }

    private fun showParityDialog(product: ProductF) {

        if (product.standardSpuIds.isNullOrEmpty()) {
            toastUI("data error")
            return
        }

        lifecycleScope.launch {
            SkGqlClient.skQuery(
                FetchProductListByStdIdQuery(
                    stdProdcutIdQuery = StdProductIdQuery(
                        stdProductId = product.standardSpuIds!!,
                        includeInValidProd = false.optional(),
                    ).optional()
                ),
                showDefaultLoading = true,
            )?.data?.fetchProductListByStdId?.run {
                this.mapNotNull { it?.productOffer }
            }?.let {
                PriceParityDialog.show(
                    supportFragmentManager,
                    product = product,
                    it,
                    spmPageValue = SpmPageDef.ProductDetailPriceParity
                )
            }
        }
    }

    //找相似
    private fun findSimilarGood() {
        viewModel.productInfo.value?.let {
            CommonRoute.toFindSimilarGoods(it.mainImg ?: "", it.id ?: "", it.type)
        }
    }

    //分享
    private fun shareGood() {
        viewModel.productInfo.value?.let {
            ShareDialog(
                mActivity,
                "${ShareUrlUtils().getUrl(ShareTypeEnum.PRODUCT)}&type=1&productId=${it.id}&standardSpuIds=${it.standardSpuIds}",
                shareCome = ShareTypeEnum.PRODUCT, imageUrl = it.mainImg
            ) {
            }.show(supportFragmentManager, "share")
        }
    }

    //上报埋点使用 字段包括 url code location
    override fun onWebLoadStatus(params: Map<String, String>) {
        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                event = TrackEvent.statistics.value,
                spmCnt = GTrackerAssistUtils.fetchElementValue(
                    SpmPageDef.ProductDetailWebView,
                    SpmElementDef.ProductUrlUnavailable
                ),
                params = params.plus("id" to (id ?: "")).plus(
                    "productId" to (productId ?: "")
                ).plus(
                    "standardSpuIds" to (standardSpuIds ?: "")
                )
            )
        )
    }

    override fun trackParams(): Map<String, String> {
        return mapOf(
            "id" to (id ?: ""),
            "productId" to (productId ?: ""),
            "standardSpuIds" to (standardSpuIds ?: ""),
            "type" to "$type",
            "merchantName" to (storeName ?: ""),
        )
    }

    override fun setPageEnf() {
        pageDef = SpmPageDef.ProductDetailWebView
    }

    override fun onResume() {
        super.onResume()
        pageExposure(
            SpmPageDef.ProductDetailWebView,
            params = mapOf("merchantName" to (storeName ?: ""))
        )
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.productInfo.observe(this) {
            //商品信息 获取比价
//            viewBinding.llGoodFsPc.visibleOrGone(true){
//                //是否显示比价
//                viewBinding.llPriceCheck.visibleOrGone(it.brotherOffers?.isNotEmpty() == true){}
//            }


            dealList =
                viewModel.productInfo.value?.dealInfoList?.mapNotNull { it?.dealVOF }
                    ?: emptyList()
            viewBinding.rlBottom.tvShowNow.visibleOrGone(
                viewModel.productInfo.value?.selfEmploymentInfo?.selfEmploymentInfoVOF?.buyButtonScript.isNullOrEmpty()
                    .not()
            )
            if (ScreenUtils.getScreenWidth2().px2dp() < 375) {//小屏幕单独处理按钮宽度
                viewBinding.rlBottom.tvShowNow.layoutParams.width = 80.dp2px()
                viewBinding.rlBottom.llOpenStore.layoutParams.width = 96.dp2px()
                viewBinding.rlBottom.llConpun.layoutParams.width = 84.dp2px()
            }
            showBottomView()
            if (viewBinding.rlBottom.tvShowNow.isVisible && viewBinding.rlBottom.tvDeals.isVisible) {
                val middleWidth = ScreenUtils.getScreenWidth2().px2dp() - 160
                viewBinding.rlBottom.llStoreBot.layoutParams.width = middleWidth.dp2px()
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    viewBinding.rlBottom.llStoreBot.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
//                        Log.e("scrollY", "======$scrollX===$oldScrollX======$scrollY===$oldScrollY")
                        if (viewBinding.rlBottom.llStoreBot.scrollX == 0) {
                            viewBinding.rlBottom.ivShawLeft.visibleOrGone(false)
                        } else {
                            viewBinding.rlBottom.ivShawLeft.visibleOrGone(true)
                        }
                        val childAt = viewBinding.rlBottom.llStoreBot.getChildAt(0)
                        if (childAt != null && childAt.measuredWidth == (viewBinding.rlBottom.llStoreBot.scrollX + viewBinding.rlBottom.llStoreBot.width)) {
                            viewBinding.rlBottom.ivShaw.visibleOrGone(false)
                        } else {
                            viewBinding.rlBottom.ivShaw.visibleOrGone(true)
                        }
                    }
                }
            }

            trackView()
        }
    }

    override fun onPause() {
        pageDisappear(
            SpmPageDef.ProductDetailWebView,
            params = mapOf("merchantName" to (storeName ?: ""))
        )
        super.onPause()
    }

    //控制显示隐藏功能按钮
//    override fun changeShowFunBtn(ifShowFunBtn: Boolean) {
//        viewBinding.llGoodFsPc.visibleOrGone(ifShowFunBtn)
//    }

    //点击分享
    fun clickFunShare() {
        shareGood()
    }
}